﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.Linq;
using Business;

namespace BVVD_Website.ql_thi_sinh
{
    public partial class frmPhongthi : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
               
                BVVDDataContext db = new BVVDDataContext();
                var list = (from kt in db.LST_KYTHIs
                            where kt.TRANGTHAI.Equals("1")
                            select kt).ToList();
                ddlKythi.DataSource = list;
                ddlKythi.DataTextField = "TENKT";
                ddlKythi.DataValueField = "MAKT";
                ddlKythi.DataBind();

                //fillgrvSobaodanh();
                grvPhongthi.DataSource = initializePT();
                grvPhongthi.DataBind();
                //lblTONGTS.Text = "--";
                

            }
        }

        protected void grvPhongthi_ItemCommand(object sender, Telerik.Web.UI.GridCommandEventArgs e)
        {
            if (e.CommandName.Equals("SavetoDB"))
            {
                if (Page.IsValid)
                {
                    BVVDDataContext db = new BVVDDataContext();
                    BVVDLibrary bl = new BVVDLibrary();
                    if (Session["ptList"] != null)
                    {
                        List<clsPhongthi> ptList = Session["ptList"] as List<clsPhongthi>;
                        List<LST_PHONGTHI> temp = new List<LST_PHONGTHI>();

                        var delPT_TS = (from del in db.F_PTHI_Ts
                                        where del.MAKT.Equals(ddlKythi.SelectedValue)
                                        select del).ToList();
                        db.F_PTHI_Ts.DeleteAllOnSubmit(delPT_TS);
                        db.SubmitChanges();
                        db.Refresh(RefreshMode.OverwriteCurrentValues, db.F_PTHI_Ts);
                        var delListPT = (from delPT in db.LST_PHONGTHIs
                                         where delPT.MAKT.Equals(ddlKythi.SelectedValue)
                                         select delPT).ToList();
                        db.LST_PHONGTHIs.DeleteAllOnSubmit(delListPT);
                        db.SubmitChanges();
                        db.Refresh(RefreshMode.OverwriteCurrentValues, db.LST_PHONGTHIs);
                        foreach (clsPhongthi pt in ptList)
                        {
                            LST_PHONGTHI lpt = new LST_PHONGTHI
                            {
                                MAKT = pt.MAKT,
                                MAPT = pt.MAPT,
                                TENPT = pt.TENPT,
                                SOTS = pt.SOTS,
                                GHICHU = pt.GHICHU

                            };
                            //temp.Add(lpt);
                            checkRowExist(lpt);
                            

                        }
                        grvPhongthi.Rebind();
                        rnAlert.Text = "Tạo phòng thi thành công ";
                        bl.createPT_TS(ddlKythi.SelectedValue);
                        rnAlert.Show();                                          
                        
                        
                    }
                    else
                    {
                        rnAlert.Text = "Nothing ";
                        rnAlert.Show();

                    }

                }
            }
        }

        private string checkRowExist(LST_PHONGTHI fc)
        {
            BVVDDataContext db = new BVVDDataContext();
            LST_PHONGTHI value = (from ck in db.LST_PHONGTHIs
                                  where ck.MAKT.Equals(fc.MAKT)
                                          && ck.MAPT.Equals(fc.MAPT)
                                  select ck).SingleOrDefault();
            if (value == null)
            {
                if (!String.IsNullOrEmpty(fc.MAKT))
                {
                    db.LST_PHONGTHIs.InsertOnSubmit(fc);
                    db.SubmitChanges();
                    return "Add";
                }
                else
                {
                    return "Dont Save";
                }
            }
            else if (!value.TENPT.Equals(fc.TENPT) || !value.SOTS.Equals(fc.SOTS))
            {
                value.TENPT = fc.TENPT;
                value.SOTS = fc.SOTS;
                db.SubmitChanges();
                return "Update";
            }
            else
            {

                return "Cancel";
            }

        }


        protected void grvPhongthi_NeedDataSource(object sender, Telerik.Web.UI.GridNeedDataSourceEventArgs e)
        {
            fillgrvPhongthi();
        }

        protected void lbtnSetAVG_Click(object sender, EventArgs e)
        {
            BVVDLibrary bl = new BVVDLibrary();
            if (Page.IsValid)
            {
                string msg = "";
                if (bl.countDT_TS(ddlKythi.SelectedValue) > 0 && bl.countPT(ddlKythi.SelectedValue) > 0)
                {
                    msg += "Tất cả các thí sinh đều đã được gán số báo danh và xếp vào phòng thi. Bạn không thể thay đổi ";
                    RadWindowManager1.RadAlert(msg, 300, 200, "Thông báo", null);
                }
                else
                {
                    msg += "Bạn đồng ý tạo phòng thi ?";


                    confirmMessage.Text = msg;
                    string script = "function f(){$find(\"" + rw_customConfirm.ClientID + "\").show(); Sys.Application.remove_load(f);}Sys.Application.add_load(f);";
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "key", script, true);
                    
                    
                }

            }
            
        }

        private void fillgrvPhongthi()
        {
            if (Session["ptList"] != null)
            {
                List<clsPhongthi> list = Session["ptList"] as List<clsPhongthi>;
                grvPhongthi.DataSource = list;

            }
            else
            {

                grvPhongthi.DataSource = initializePT();
            }

        }

        private List<clsPhongthi> initializePT()
        {
            BVVDDataContext db = new BVVDDataContext();
            var list = (from pt in db.LST_PHONGTHIs
                        where pt.MAKT.Equals(ddlKythi.SelectedValue)
                        select new clsPhongthi
                        {
                            RECID = pt.RECID,
                            MAKT = pt.MAKT,
                            TENKT = pt.LST_KYTHI.TENKT,
                            MAPT = pt.MAPT,
                            TENPT = pt.TENPT,
                            SOTS = pt.SOTS.GetValueOrDefault(0),
                            GHICHU = pt.GHICHU
                        }).ToList();
            return list;

        }

        protected void rbConfirm_OK_Click(object sender, EventArgs e)
        {
            BVVDLibrary bl = new BVVDLibrary();
            int totalTS = Convert.ToInt32(bl.countTS(ddlKythi.SelectedValue));
            if (totalTS > 0)
            {
                int avg = Convert.ToInt32(txtAVG.Value.GetValueOrDefault(20));
                int number_room;
                List<clsPhongthi> ptList = new List<clsPhongthi>();
                if (totalTS % avg > 0)
                {
                    number_room = totalTS / avg + 1;
                }
                else
                {
                    number_room = totalTS / avg;
                }

                if (Page.IsValid)
                {
                    for (int i = 1; i < number_room; i++)
                    {
                        string mapt = "PT" + i.ToString().PadLeft(3, '0');
                        string tenpt = "Phòng thi số " + i;
                        clsPhongthi pt = new clsPhongthi(i, ddlKythi.SelectedValue, ddlKythi.SelectedText, mapt, tenpt, avg, "");
                        ptList.Add(pt);
                    }
                    if (totalTS % avg > 0)
                    {
                        string mapt = "PT" + number_room.ToString().PadLeft(3, '0');
                        string tenpt = "Phòng thi số " + number_room;
                        clsPhongthi pt = new clsPhongthi(number_room, ddlKythi.SelectedValue, ddlKythi.SelectedText, mapt, tenpt, totalTS % avg, "");
                        ptList.Add(pt);
                    }
                    else
                    {
                        string mapt = "PT" + number_room.ToString().PadLeft(3, '0');
                        string tenpt = "Phòng thi số " + number_room;
                        clsPhongthi pt = new clsPhongthi(number_room, ddlKythi.SelectedValue, ddlKythi.SelectedText, mapt, tenpt, avg, "");
                        ptList.Add(pt);

                    }

                    Session["ptList"] = ptList;
                    
                    grvPhongthi.Rebind();
                    
                    

                }
            }
            else
            {
                rnAlert.Text = "Danh sách thí sinh -  số báo danh trong kỳ thi " + ddlKythi.SelectedText + " hiện chưa có. Vui lòng tạo số báo danh cho thí sinh ";
                rnAlert.Show();

            }
            
            
        }

        protected void ddlKythi_SelectedIndexChanged(object sender, Telerik.Web.UI.DropDownListEventArgs e)
        {
            BVVDLibrary bl = new BVVDLibrary();
            lblTONGTS.Text = bl.countTS(ddlKythi.SelectedValue).ToString();
            initializePT();
            Session["ptList"] = null;
            fillgrvPhongthi();
            grvPhongthi.DataBind();
        }




    }

    public class clsPhongthi
    {
        public int RECID { get; set; }
        public string MAKT { get; set; }
        public string TENKT { get; set; }
        public string MAPT { get; set; }
        public string TENPT { get; set; }
        public int SOTS { get; set; }
        public string GHICHU { get; set; }

        public clsPhongthi()
        {

        }

        public clsPhongthi(int recid, string makt, string tenkt, string mapt, string tenpt, int sots, string ghichu)
        {
            RECID = recid;
            MAKT = makt;
            TENKT = tenkt;
            MAPT = mapt;
            TENPT = tenpt;
            SOTS = sots;
            GHICHU = ghichu;

        }

    }
}